package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.service.UserService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private WebSocketServer webSocketServer;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;

    @Override
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        //1.处理业务异常逻辑
        //收货地址为空
        AddressBook addressBook=addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if(addressBook==null){
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //购物车为空
        List<ShoppingCart> shoppingCartList=shoppingCartMapper.list(ShoppingCart.builder().userId(BaseContext.getCurrentId()).build());
        if (shoppingCartList==null||shoppingCartList.size()==0) {
            throw new AddressBookBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //2.插入一条订单数据
        Orders orders=new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,orders);
        orders.setPayStatus(Orders.UN_PAID);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPhone(addressBook.getPhone());
        orders.setUserId(BaseContext.getCurrentId());
        orders.setAddress(addressBook.getProvinceName()+addressBook.getCityName()+addressBook.getDistrictName()+addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setUserName(userService.getById(BaseContext.getCurrentId()).getName());
        orders.setNumber(String.valueOf(System.currentTimeMillis()));

        orderMapper.insert(orders);

        //3.插入多条订单明细数据
        List<OrderDetail> orderDetailList=new ArrayList<>();
        for (ShoppingCart shoppingCart : shoppingCartList) {
            OrderDetail orderDetail=new OrderDetail();
            BeanUtils.copyProperties(shoppingCart,orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        }
        orderDetailMapper.insertBatch(orderDetailList);
        //4.清理购物车中的数据
        shoppingCartMapper.deleteByUserId(BaseContext.getCurrentId());
       OrderSubmitVO orderSubmitVO=OrderSubmitVO.builder().
               orderNumber(orders.getNumber()).
               orderTime(orders.getOrderTime()).
               id(orders.getId()).orderAmount(orders.getAmount()).build();
       return orderSubmitVO;

    }
    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

//        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );
        //生成空json，跳过微信支付流程
     JSONObject jsonObject=new JSONObject();
        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void  paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();
        orderMapper.update(orders);
        Map map=new HashMap();
        map.put("type",1);//消息类型，1表示来单提醒
        map.put("orderId",orders.getId());
        map.put("content","订单号："+outTradeNo);
        webSocketServer.sendToAllClient(JSONObject.toJSONString(map));

    }

    @Override
    public PageResult pageHistory(int pageNum, int pageSize, Integer status) {
        PageHelper.startPage(pageNum,pageSize);
        OrdersPageQueryDTO ordersPageQueryDTO=new OrdersPageQueryDTO();
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        ordersPageQueryDTO.setStatus(status);
        Page<Orders> page=orderMapper.pageQuery(ordersPageQueryDTO);
        List<OrderVO> list=new ArrayList<>();
        for (Orders orders : page) {
            List<OrderDetail>  orderDetailList=orderDetailMapper.getByOrderId(orders.getId());
            OrderVO orderVO=new OrderVO();
            BeanUtils.copyProperties(orders,orderVO);
            orderVO.setOrderDetailList(orderDetailList);
            list.add(orderVO);
        }
        return new PageResult(page.getTotal(),list);
    }

    @Override
    public OrderVO details(Long id) {
        Orders orders=orderMapper.getById(id);
        OrderVO orderVO=new OrderVO();
        List<OrderDetail> orderDetailList=orderDetailMapper.getByOrderId(id);
        orderVO.setOrderDetailList(orderDetailList);
        BeanUtils.copyProperties(orders,orderVO);
        return orderVO;
    }

    @Override
    public void cancel(Long id) throws Exception {
        //根据id查询订单
        Orders ordersDB=orderMapper.getById(id);
        //验证订单是否存在
        if (ordersDB==null) {
         throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
         Orders orders=new Orders();
        orders.setId(id);
        // 订单处于待接单状态下取消，需要进行退款
        if (ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            //调用微信支付退款接口
//            weChatPayUtil.refund(
//                    ordersDB.getNumber(), //商户订单号
//                    ordersDB.getNumber(), //商户退款单号
//                    new BigDecimal(0.01),//退款金额，单位 元
//                    new BigDecimal(0.01));//原订单金额

            //支付状态修改为 退款
            orders.setPayStatus(Orders.REFUND);
        }
        //更新订单状态
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelTime(LocalDateTime.now());
        orders.setCancelReason("用户取消");
        orderMapper.update(orders);
    }


    @Override
    public void repetition(Long id) {
        //再来一单就是把当前订单加入购物车中
      Orders ordersDB=orderMapper.getById(id);
      if (ordersDB==null) {
          throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
      }
         List<OrderDetail> list=orderDetailMapper.getByOrderId(id);
         List<ShoppingCart> shoppingCartList=new ArrayList<>();
         for (OrderDetail orderDetail : list) {
             ShoppingCart shoppingCart=new ShoppingCart();
             BeanUtils.copyProperties(orderDetail,shoppingCart,"id");
             shoppingCart.setCreateTime(LocalDateTime.now());
             shoppingCart.setUserId(BaseContext.getCurrentId());
             shoppingCartList.add(shoppingCart);
         }
         shoppingCartMapper.insertBatch(shoppingCartList);
    }

    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        //开始分页查询
         PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
         //商家需要查询到所有用户的订单信息，故不需要userid
         //ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
          Page<Orders> orderslist= orderMapper.pageQuery(ordersPageQueryDTO);
           List<OrderVO> list=new ArrayList<>();
           for (Orders orders : orderslist) {
               OrderVO orderVO=new OrderVO();
               BeanUtils.copyProperties(orders,orderVO);
               List<OrderDetail> orderDetailList=orderDetailMapper.getByOrderId(orders.getId());
               orderVO.setOrderDetailList(orderDetailList);
               List<String> DishNameList=new ArrayList<>();
               for (OrderDetail orderDetail : orderDetailList) {
                        DishNameList.add(orderDetail.getName());
               }
               orderVO.setOrderDishes(StringUtils.join(DishNameList,";"));
               list.add(orderVO);
           }

           return new PageResult(orderslist.getTotal(),list);
    }

    @Override
    public OrderStatisticsVO statistics() {
       //OrderStatisticsVO orderStatisticsVO=orderMapper.statistic();
        //暴力方法，把每一种结果查出来，待优化
        OrderStatisticsVO orderStatisticsVO=new OrderStatisticsVO();
        orderStatisticsVO.setConfirmed(orderMapper.statistic(Orders.CONFIRMED));
        orderStatisticsVO.setToBeConfirmed(orderMapper.statistic(Orders.TO_BE_CONFIRMED));
        orderStatisticsVO.setDeliveryInProgress(orderMapper.statistic(Orders.DELIVERY_IN_PROGRESS));

        return orderStatisticsVO;
    }

    @Override
    public void confirm(Long id) {
        Orders orders= Orders.builder().id(id).status(Orders.CONFIRMED).build();

        orderMapper.update(orders);
    }

    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        Orders ordersDB=orderMapper.getById(ordersRejectionDTO.getId());
        if(ordersDB==null||!ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //如果订单已支付则要进行退款
        if(ordersDB.getPayStatus().equals(Orders.PAID)){
            ordersDB.setPayStatus(Orders.REFUND);
        }
            Orders orders=Orders.builder().id(ordersRejectionDTO.
                    getId()).status(Orders.CANCELLED).
                    payStatus(ordersDB.getPayStatus()).cancelReason(ordersRejectionDTO.getRejectionReason())
                    .cancelTime(LocalDateTime.now()).build();
            orderMapper.update(orders);
    }

    @Override
    public void cancelByAdmin(OrdersCancelDTO ordersCancelDTO) {
        Orders ordersDB=orderMapper.getById(ordersCancelDTO.getId());
        //如果订单已支付则要进行退款
        if(ordersDB.getPayStatus().equals(Orders.PAID)){
            ordersDB.setPayStatus(Orders.REFUND);
        }
        Orders orders=Orders.builder().id(ordersCancelDTO.
                        getId()).status(Orders.CANCELLED).
                payStatus(ordersDB.getPayStatus()).cancelReason(ordersCancelDTO.getCancelReason())
                .cancelTime(LocalDateTime.now()).build();
        orderMapper.update(orders);
    }

    @Override
    public void delivery(Long id) {
        Orders ordersDB=orderMapper.getById(id);
        if(ordersDB.getStatus().equals(Orders.CONFIRMED)&&ordersDB!=null){
            //更新订单状态
            Orders orders=Orders.builder().id(id).status(Orders.DELIVERY_IN_PROGRESS).build();
            orderMapper.update(orders);
        }else{
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
    }

    @Override
    public void complete(Long id) {
        Orders ordersDB=orderMapper.getById(id);
        // 校验订单是否存在，并且状态为4
        if(!ordersDB.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)||ordersDB==null){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orders=Orders.builder().id(id).status(Orders.COMPLETED).deliveryTime(LocalDateTime.now()).build();
        orderMapper.update(orders);
    }

    @Override
    public void reminder(Long id) {
        // 查询订单是否存在
        Orders orders = orderMapper.getById(id);
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);

        }
    Map map=new HashMap();
    map.put("orderId",id);
    map.put("type",2);//2表示用户催单
    map.put("content","订单号："+orders.getNumber());
    webSocketServer.sendToAllClient(JSONObject.toJSONString(map));

    }
}
